package com.itheima.project.adepter.impl;

import com.itheima.project.adepter.LoginAuthAdepter;
import com.itheima.project.constant.security.EnterpriseCacheConstant;
import com.itheima.project.constant.security.OauthConstant;
import com.itheima.project.core.enums.security.AuthEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.handler.LoginAuthHandler;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.RegisterBeanHandler;
import com.itheima.project.vo.security.EnterpriseVo;
import com.itheima.project.vo.security.UserVo;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Map;

/**
 * @ClassName LoginAuthAdepterImpl.java
 * @Description 登录适配器
 */
@Component
public class LoginAuthAdepterImpl implements LoginAuthAdepter {

    @Autowired
    RegisterBeanHandler registerBeanHandler;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    HttpServletRequest httpServletRequest;


    @Override
    public EnterpriseVo findEnterpriseVoByHost() {
        //获得域名
        String host = httpServletRequest.getHeaders("x-forwarded-host")
                .nextElement().split(",")[0].split(":")[0];
        String key = EnterpriseCacheConstant.WEBSITE+host;
        RBucket<EnterpriseVo> bucket = redissonClient.getBucket(key);
        EnterpriseVo enterpriseVo = bucket.get();
        if (EmptyUtil.isNullOrEmpty(enterpriseVo)){
            throw  new ProjectException(AuthEnum.HSOT_FAIL);
        }
        return enterpriseVo;
    }

    @Override
    public UserVo adepterRoutes(Principal principal, Map<String, String> parameters)
            throws HttpRequestMethodNotSupportedException {
        //获得域名
        String host = httpServletRequest.getHeaders("x-forwarded-host").nextElement().split(",")[0].split(":")[0];
        String key = EnterpriseCacheConstant.WEBSITE+host;
        //域名校验
        RBucket<EnterpriseVo> bucket = redissonClient.getBucket(key);
        EnterpriseVo enterpriseVo = bucket.get();
        if (EmptyUtil.isNullOrEmpty(enterpriseVo)){
            throw  new ProjectException(AuthEnum.HSOT_FAIL);
        }
        //适配登录方式
        String loginType = parameters.get(OauthConstant.LOGIN_TYPE_KEY);
        if (EmptyUtil.isNullOrEmpty(loginType)){
            throw  new ProjectException(AuthEnum.LOGIN_FAIL);
        }
        String loginTypeBeanName = OauthConstant.LoginAuthHandlers.get(loginType.split("-")[1]);
        LoginAuthHandler loginAuthHandler = registerBeanHandler.getBean(loginTypeBeanName,LoginAuthHandler.class);
        return loginAuthHandler.loginHandler(principal,parameters,enterpriseVo);
    }
}
